<template>
  <el-dialog title="训练默认配置" width="45%" v-model="state.visible">
    <div>
      <el-form size="large" :model="mSelectedValue">
        <div v-for="item in addFormRef">
          <!-- 输入框 -->
          <el-form-item
            :label="item.help"
            label-position="top"
            v-show="InputOrNotBox(item)"
          >
            <el-input
              v-model="item.def"
              @change="OnlyWhenModelValueChanges(item)"
            />
          </el-form-item>
          <!-- 选择框 -->
          <el-form-item
            :label="item.help"
            label-position="top"
            v-show="SelectionModel(item)"
          >
            <!-- 选择框 -->
            <el-select
              v-model="ModelName"
              placeholder="请选择一个模型名称"
              size="large"
              @change="TriggeredWhenSelectedValueChanges(item)"
            >
              <el-option
                v-for="choices in item.choices"
                :key="choices"
                :label="choices"
                :value="choices"
              />
            </el-select>
          </el-form-item>
          <!-- 复选框 -->

          <el-form-item
            :label="item.help"
            label-position="top"
            v-show="SwitchSelect(item)"
          >
            <el-switch
              v-model="item.required"
              @change="switchCallbackFunctionWhenTtateChanges(item)"
            />
          </el-form-item>
        </div>
      </el-form>
    </div>

    <template #footer>
      <el-space>
        <el-button @click="() => (state.visible = false)">取消</el-button>
        <el-button type="primary" @click="startActuator()">确认</el-button>
      </el-space>
    </template>
  </el-dialog>
</template>

<script setup>
/**
 *
 */
import { reactive, ref, onMounted } from "vue";
/**
 *  训练配置
 */
import TrainingConfiguration from "@/api/modules/TrainingConfiguration.js";
/**
 *
 */
import { requestedMessage } from "@/utils/requested_utils";
/**
 *
 */
import {
  InputOrNotBox,
  SelectionModel,
  SwitchSelect,
} from "@/utils/common_utils";
/**
 * 存储
 */
import storageService from "@/utils/dataStore_utils";

/**
 * 数据集数据
 */
const addFormRef = ref();
/**
 * 选中值
 */
const mSelectedValue = ref([]);
/**
 *
 */
const state = reactive({
  visible: false,
  trainingSetId: "",
  rules: {
    choices: [{ required: "true", message: "请选择模型名称", trigger: "blur" }],
  },
});
/**
 * 模型名称
 */
const ModelName = ref();
/**
 * 现在
 */

/**
 * 生命周期
 */
onMounted(() => {
  /**
   *
   */
  getActuatorConfig();
});

/**
 * 获取训练默认配置
 */
function getActuatorConfig() {
  requestedMessage(
    async () => {
      const { message, msg } = await TrainingConfiguration.getActuatorConfig();
      addFormRef.value = message.list;
      return msg;
    },
    {
      showSuccess: true,
      fullscreenLoading: true,
    }
  );
}

/**
 * 选中值发生变化时触发
 */
function TriggeredWhenSelectedValueChanges(item) {
  //键
  const key = item.name;
  //值
  const value = ModelName.value;

  // 使用 .value 访问和修改 ref 包装的值
  const existingIndex = mSelectedValue.value.findIndex(
    (item) => item.key === key
  );
  if (existingIndex > -1) {
    // 如果找到了匹配项，则更新该项
    mSelectedValue.value[existingIndex] = { key, value };
  } else {
    // 如果没有找到匹配项，则添加新项
    mSelectedValue.value.push({ key, value });
  }
}

/**
 * 仅当 modelValue 改变时，当输入框失去焦点或用户按Enter时触发
 */
function OnlyWhenModelValueChanges(item) {
  //键
  const key = item.name;
  //值
  const value = item.def;
  // 使用 .value 访问和修改 ref 包装的值
  const existingIndex = mSelectedValue.value.findIndex(
    (item) => item.key === key
  );
  if (existingIndex > -1) {
    // 如果找到了匹配项，则更新该项
    mSelectedValue.value[existingIndex] = { key, value };
  } else {
    // 如果没有找到匹配项，则添加新项
    mSelectedValue.value.push({ key, value });
  }
}

/**
 * switch 状态发生变化时的回调函数
 */
function switchCallbackFunctionWhenTtateChanges(item) {
  //键
  const key = item.name;
  //值
  const value = item.required;

  // 使用 .value 访问和修改 ref 包装的值
  const existingIndex = mSelectedValue.value.findIndex(
    (item) => item.key === key
  );
  if (existingIndex > -1) {
    // 如果找到了匹配项，则更新该项
    mSelectedValue.value[existingIndex] = { key, value };
  } else {
    // 如果没有找到匹配项，则添加新项
    mSelectedValue.value.push({ key, value });
  }
}

/**
 * 确认开始训练
 */
async function startActuator() {
  console.log("+++++++", mSelectedValue.value);

  // 构建配置对象
  const config = {
    trainingSetId: storageService.sessionData.TheDataSetid,
  };

  // 动态添加配置项
  mSelectedValue.value.forEach((item) => {
    config[item.key] = item.value;
  });

  requestedMessage(
    async () => {
      const { msg } = await TrainingConfiguration.startActuator(config);
      state.visible = false;
      return msg;
    },
    {
      showSuccess: true,
      fullscreenLoading: true,
    }
  );
}

// 开启弹窗
const open = (row) => {
  state.visible = true;
  if (null != row) {
    console.log("修改弹框");
  } else {
    console.log("开启弹窗");
  }
};

// 关闭弹窗
const close = () => {
  state.visible = false;
  console.log("关闭弹窗" + state.visible);
};

defineExpose({ open, close });
</script>
